#include <cstdlib>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */

#include "arduino.h"
using namespace std;

int openPort()
{
    int fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1)
    {
        cerr << "Unable to open port\n";
        return -1;
    }
    else
    {
        fcntl(fd, F_SETFL, 0);
        cout << "Port opened succesfully\n";
    }
    return fd;
}

int configPort(int fd)
{
    struct termios options;
    //Get the current options for the port...
    tcgetattr(fd, &options);
    //set baudrate
    cfsetispeed(&options, B38400);
    cfsetospeed(&options, B38400);
    //set parity checking
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    int n = tcsetattr(fd, TCSAFLUSH, &options);
    if (n < 0)
    {
        cerr << "Port configuration fail\n";
        return n;
    }
    else
        return 0;
}

int arduino(int fd, const char data[])
{       
    int wr, rd;
    char reply;
    
    cout << "Write: " << data << "\n";
    
    wr = write(fd, data, 4);
                        
    if (wr < 1)
    {
        cerr << "Write failed\n";
        return -1;
    }

    rd = read(fd, &reply, 1);
            
    while (rd < 1)
    {
        cerr << "Read failed\n";
        rd = read(fd, &reply, 1);
    }
    if (reply == 'y')
        return 0;
    else
        return -1;  
}